using System.Reflection;
using UnityEngine;

namespace NodeCanvas.Actions
{
	[Category("✫ Script Control")]
	[Description("Calls a function that has signature of 'public Status NAME()'. Return Status.Success, Failure or Running within that function")]
	[AgentType(typeof(Transform))]
	public class ImplementedAction : ActionTask
	{
		[RequiredField]
		public string methodName;

		[RequiredField]
		public string scriptName;

		private Component script;

		private MethodInfo method;

		private Status status = Status.Resting;

		protected override string info
		{
			get
			{
				return string.Format("({0}.{1})", base.agentInfo, methodName);
			}
		}

		protected override string OnInit()
		{
			script = base.agent.GetComponent(scriptName);
			if (script == null)
			{
				return "Can't find script";
			}
			method = script.GetType().NCGetMethod(methodName);
			if (method == null)
			{
				return "Method not found";
			}
			return null;
		}

		protected override void OnExecute()
		{
			Forward();
		}

		protected override void OnUpdate()
		{
			Forward();
		}

		private void Forward()
		{
			status = (Status)method.Invoke(script, null);
			if (status == Status.Success)
			{
				EndAction(true);
			}
			else if (status == Status.Failure)
			{
				EndAction(false);
			}
		}

		protected override void OnStop()
		{
			status = Status.Resting;
		}
	}
}
